package com.haojiang.mh.ui.fragment

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.View
import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.remote.utils.BleUtil.Companion.permissionArr
import com.haojiang.mh.remote.utils.Util
import com.haojiang.mh.service.ble.BleHandle
import com.haojiang.mh.service.entity.BleNewData
import com.haojiang.mh.service.event.OneEvent
import com.haojiang.mh.ui.activity.DeviceListActivity
import com.haojiang.mh.ui.base.LazyLoadBaseFragment
import com.haojiang.mh.utils.SpUtil
import com.haojiang.mh.widget.CommonDialog
import com.haojiang.mh.widget.TopTabLayout
import com.haojiang.mh.widget.popup.BedStatusPopup
import com.lx.permission.IPermissionCallback
import com.lx.permission.PermissionManager
import com.yanzhenjie.permission.AndPermission
import kotlinx.android.synthetic.main.fragment_two.*
import kotlinx.android.synthetic.main.layout_stub_device_offline.*
import kotlinx.android.synthetic.main.layout_stub_no_device.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 设备监测
 *
 * Created by ZapFive on 2019-05-25.
 *
 * wuzhuang@mirahome.me
 */
class TwoFragment : LazyLoadBaseFragment() {

    private var currSide = 0//0:左边  1:右边
    private var layoutDeviceOffline: View? = null
    private var layoutNoDevice: View? = null
    private var statusPopup: BedStatusPopup? = null

    override fun getLayoutId() = R.layout.fragment_two

    override fun initView() {
        topTabLayout.setOnTabSelectListener { selectTabIndex, _, flag ->
//            if (flag != TopTabLayout.SLIDE_END) return@setOnTabSelectListener
            currSide = selectTabIndex
            showMonitorData(BleHandle.instance.bleNewData ?: BleNewData())
        }
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
        refreshView()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            0xAAAA -> context.showLongToast(getString(R.string.tip_open_bluetooth))
            0xBBBB -> context.showLongToast(getString(R.string.tip_granted_location))
            0xCCCC -> context.showLongToast(getString(R.string.tip_open_location))
        }
    }

    /**
     * 刷新View
     */
    private fun refreshView() {
        if (SpUtil[Const.DEVICE_MAC, ""].isEmpty()) {
            showNoDeviceStub()
        } else {
            if (BleHandle.instance.isConnected()) {
                hideAllViewStub()
                val isDouble = SpUtil[Const.IS_DOUBLE_MODE, true]
                topTabLayout.visibility = if (isDouble) View.VISIBLE else View.GONE
                layout_top_single.visibility = if (isDouble) View.GONE else View.VISIBLE
                showMonitorData(BleHandle.instance.bleNewData ?: BleNewData())
            } else {
                showDeviceOfflineStub()
                checkBluetoothAndPermission()
            }
        }
    }

    //region 蓝牙和位置权限
    /**
     * 蓝牙定位权限
     */
    private fun checkBluetoothAndPermission() {
        if (!BleHandle.instance.isSupportBle()) {
            context.showLongToast(getString(R.string.tip_not_support_ble))
            return
        }
        if (!BleHandle.instance.isBleEnable()) {
            val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(intent, 0xAAAA)
            return
        }
        checkPermission()
    }

    /**
     * 确定权限
     */
    private fun checkPermission() {
        if (AndPermission.hasPermissions(context, Manifest.permission.ACCESS_FINE_LOCATION)) {
            onPermissionGranted()
        } else {
            CommonDialog.Builder(context, 1)
                .setContent(getString(R.string.tip_granted_location))
                .setRightClick { _, _ ->
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    intent.data = Uri.fromParts("package", context.packageName, null)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    context.startActivityForResult(intent, 0xBBBB)
                }
                .create().show()
        }
    }

    /**
     * 获取权限
     */
    private fun onPermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
            CommonDialog.Builder(context, 1)
                .setContent(getString(R.string.tip_open_location))
                .setRightClick { _, _ ->
                    val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                    startActivityForResult(intent, 0xCCCC)
                }
                .create().show()
        } else {
            context.showLoadingDialog()
            BleHandle.instance.connectDevice(true)
        }
    }

    /**
     * 确定GPS打开
     */
    private fun checkGPSIsOpen(): Boolean {
        val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
    }
    //endregion




    //region Listener
    private val retryConnect = View.OnClickListener {
        checkBluetoothAndPermission()
    }

    private val mIPermissionCallback = IPermissionCallback {
        context.redirectNoParam(DeviceListActivity::class.java)
    }

    private val addDevice = View.OnClickListener {
        if (!Util.checkBleStatus(context)) return@OnClickListener
        //申请权限
        PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback, 0)
        PermissionManager.getInstance().requestPermission(
            context,
            permissionArr
        )
    }

    //endregion

    //region ViewStub
    private fun hideAllViewStub() {
        layoutNoDevice?.visibility = View.GONE
        layoutDeviceOffline?.visibility = View.GONE
        layout_data.visibility = View.VISIBLE
    }

    /**
     * 设备离线
     */
    private fun showDeviceOfflineStub() {
        if (layoutDeviceOffline == null) {
            layoutDeviceOffline = vs_device_offline.inflate()
            bt_retry.setOnClickListener(retryConnect)
        } else {
            if (layoutDeviceOffline?.visibility == View.VISIBLE) return
            layoutDeviceOffline?.visibility = View.VISIBLE
        }
        layoutNoDevice?.visibility = View.GONE
        showMonitorData()
        layout_data.visibility = View.GONE
    }

    /**
     * 无设备
     */
    private fun showNoDeviceStub() {
        if (layoutNoDevice == null) {
            layoutNoDevice = vs_no_device.inflate()
            bt_add.setOnClickListener(addDevice)
        } else {
            if (layoutNoDevice?.visibility == View.VISIBLE) return
            layoutNoDevice?.visibility = View.VISIBLE
        }
        layoutDeviceOffline?.visibility = View.GONE
        showMonitorData()
        layout_data.visibility = View.GONE
    }

    //endregion

    /**
     * 更新最新的体征数据
     */
    private fun showMonitorData(data: BleNewData = BleNewData()) {
        val isShowRight = SpUtil[Const.IS_DOUBLE_MODE, true] && currSide == 1
        tv_heart_rate.text = "${if (isShowRight) data.Right.HD else data.Left.HD}"
        tv_breath_rate.text = "${if (isShowRight) data.Right.BD else data.Left.BD}"
        val move = if (isShowRight) data.Right.IsMove == 1 else data.Left.IsMove == 1
        tv_body_move.text = getString(if (move) R.string.txt_movement_have else R.string.txt_movement_not)
        val onBed = if (isShowRight) data.Right.IsOnBed == 1 else data.Left.IsOnBed == 1
        tv_bed_state.text = getString(if (onBed) R.string.text_on_bed else R.string.text_leave_bed)
        val isNeedShowPopup = if (isShowRight) data.Right.Std == 2 else data.Left.Std == 2
        showStatusPopup(isNeedShowPopup)
    }

    /**
     * 检测不稳定时弹窗
     */
    private fun showStatusPopup(isShow: Boolean) {
        if (isShow) {
            if (statusPopup == null) {
                statusPopup = BedStatusPopup(context)
                statusPopup?.setBackgroundColor(0x1C000000)
            }
            if (!statusPopup!!.isShowing) {
                statusPopup?.showPopupWindow(view_show_popup)
            }
        } else {
            statusPopup?.dismiss()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveNewData(data: BleNewData) {
        showMonitorData(data)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveEvent(event: OneEvent) {
        when (event.type) {
            Const.CONNECT_DEVICE -> {
                context.hideLoadingDialog()
                if (event.getIntValue() == Const.OK_RESULT) {
                    refreshView()
                } else {
                    context.showToast(R.string.tip_not_search_device)
                }
            }
            Const.DISCONNECT_DEVICE -> refreshView()
        }
    }
}